package com.auxgroup.smarthome.business.controller;

import com.auxgroup.bridge.app.inner.vo.AppUserVo;
import com.auxgroup.bridge.business.inner.vo.UserDeviceListVo;
import com.auxgroup.smarthome.business.service.AppUserService;
import com.auxgroup.smarthome.business.service.DeviceService;
import com.auxgroup.smarthome.business.util.DownloadForResponseUtil;
import com.auxgroup.smarthome.business.vo.AppExportTitleVo;
import com.auxgroup.smarthome.filter.annotation.PermissionFilter;
import com.auxgroup.smarthome.syscode.BusinessCode;
import com.auxgroup.smarthome.utils.JsonValidator;
import com.auxgroup.smarthome.utils.excel.Excel;
import com.auxgroup.smarthome.utils.excel.constant.SheetVersion;
import com.auxgroup.smarthome.web.ApiResponse;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/8/14 9:13.
 */
@Api(tags = "app用户管理")
@RestController
@RequestMapping("/app")
public class AppUserController {
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private DeviceService deviceService;

    @ApiOperation(value = "获取App用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keywords", value = "用户名/用户名/手机号",  paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "page", value = "页码",  paramType = "query", dataType = "integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "分页大小",  paramType = "query", dataType = "integer", defaultValue = "20")
    })
    @GetMapping("/users")
    public ApiResponse<Page<AppUserVo>> getAppUserList(@ApiIgnore String keywords, @ApiIgnore Integer page, @ApiIgnore Integer size) {
        return appUserService.getAppUserList(keywords, page, size);
    }

    @ApiOperation(value = "获取App用户详情")
    @GetMapping("/users/{uid}")
    public ApiResponse<AppUserVo> getAppUserDetail(@PathVariable("uid") String uid) {
        return appUserService.getAppUser(uid);
    }

    @ApiOperation(value = "获取App用户设备列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码",  paramType = "query", dataType = "integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "分页大小",  paramType = "query", dataType = "integer", defaultValue = "20")
    })
    @GetMapping("/users/{uid}/devices")
    public ApiResponse<Page<UserDeviceListVo>> getAppUserDeviceList(@PathVariable("uid") String uid, @ApiIgnore Integer page, @ApiIgnore Integer size) {
        return deviceService.getUserDeviceList(uid, page, size);
    }

    @ApiOperation(value = "导出App用户列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keywords", value = "用户名/用户名/手机号",  paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "exportType", value = "导出类型：0：全部批量，1：筛选结果", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "exportFields", value = "导出字段JSON示例：{\"uid\" : \"用户UID\"}", paramType = "query", dataType = "string", required = true)

    })
    @PermissionFilter(filter = true)
    @GetMapping("/users/export_data")
    public ApiResponse exportAppuserData(String keywords, @Range(min = 0, max = 1, message = "exportType必选传0或1") int exportType, @NotBlank(message = "导出字段必填") String exportFields, HttpServletResponse response) throws Exception {
        if (!JsonValidator.INSTANCE.validate(exportFields)) {
            return ApiResponse.prompt(BusinessCode.DTO_PARAMS_ERROR.getCode(), "exportFields不是有效的json");
        }
        // 所有的导出字段
        final List<String> AllExportFields = Arrays.asList(new String[] {"uid", "nickName", "phone", "realName", "createdAt", "gender"});

        Gson gson = new Gson();
        Map<String, String> titleMap = gson.fromJson(exportFields, Map.class);
        List<String> titleList = new ArrayList<>(titleMap.keySet());

        // 不支持的字段
        StringBuilder unsupportFields = new StringBuilder();

        titleList.stream().forEach(title -> {
            if (!AllExportFields.contains(title)) {
                unsupportFields.append(title).append(",");
            }
        });

        if (unsupportFields.length() != 0) {
            unsupportFields.append("不支持的导出字段");
            return ApiResponse.prompt(BusinessCode.DTO_PARAMS_ERROR.getCode(), unsupportFields.toString());
        }

        // exportType = 0 导出全部数据
        if(exportType == 0) {
           keywords = null;
        }

        ApiResponse<List<AppUserVo>> apiResponse = appUserService.getAllAppUser(keywords);
        if (apiResponse.getCode() != 200) {
            return apiResponse;
        }
        List<AppUserVo> appUserVoList = apiResponse.getData();

        if (null == appUserVoList) {
            return ApiResponse.fail();
        }

        List<AppExportTitleVo> exportData = new ArrayList<>();

        for(AppUserVo appUserVo: appUserVoList) {
            exportData.add(AppExportTitleVo.createExportData(appUserVo));
        }


        Excel excel = new Excel(SheetVersion.EXCEL2007_SXSSF);

        // 设置标题, 设置水平对齐方式
        excel.row(0)
                .value(titleMap.values().toArray())
                .bold()
                .align(HorizontalAlignment.CENTER);

        DownloadForResponseUtil.setExcelData(excel, exportData, titleList, AppExportTitleVo.class);

        // 冻结第一行，重命名当前处于工作状态的表的名称
        excel.sheet().freeze(1, 0)
                .sheetName("app用户列表");

        DownloadForResponseUtil.downloadExcel(excel.getWorkbook(), "aux_app_user", response);
        return null;
    }

}
